package com.cqhz.quwan.ui.buy.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.SoundPool
import android.os.Build
import android.os.Bundle
import android.os.Vibrator
import android.support.annotation.RequiresApi
import android.text.Html
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.BettingItem
import com.cqhz.quwan.model.Lottery
import com.cqhz.quwan.model.NumType
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.buy.BettingMachineActivity
import com.cqhz.quwan.ui.buy.LotteryBettingActivity
import com.cqhz.quwan.ui.widget.NumberSelectorView
import com.cqhz.quwan.util.combine
import com.cqhz.quwan.util.findDuplicate
import com.cqhz.quwan.util.findView

class BettingNumberFragment : AbsFragment() {
    private val tipLabelTv by findView<TextView>(R.id.number_tip_label)
    private val numberSelectorView by findView<NumberSelectorView>(R.id.number_selector)
    private val resultLabel by findView<TextView>(R.id.label_result)
    private val machineSelectBtn by findView<TextView>(R.id.tv_machine_select)
    private val shakeBtn by findView<TextView>(R.id.tv_shake)
    private val clearBtn by findView<TextView>(R.id.tv_ball_clear)
    private val confirmBtn by findView<TextView>(R.id.btn_confirm)
    private val numbers = ArrayList<ArrayList<Int>>()
    private var method:NumType.BetMethod? = null
    private var allStake = 0L
    private lateinit var mSensorManager: SensorManager
    private lateinit var mVibrator: Vibrator
    private lateinit var mSoundPool: SoundPool
    private var mSoundId:Int = -1
    private var mOldShakeTime:Long = -1
    private val mSensorEventListener = object : SensorEventListener {
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {

        }

        override fun onSensorChanged(event: SensorEvent?) {
            val sensorType = event?.sensor?.type
            val values = event?.values
            if(sensorType == Sensor.TYPE_ACCELEROMETER){
                if((Math.abs(values!![0]) > SENSOR_VALUE
                                || Math.abs(values[1]) > SENSOR_VALUE
                                || Math.abs(values[2]) > SENSOR_VALUE)){
                    val t = System.currentTimeMillis() - mOldShakeTime
                    if(t >= 1500){
                        mVibrator.vibrate(100)
                        mSoundPool.play(mSoundId,1f,1f,1,0,1f)
                        numberSelectorView?.randoms()
                        mOldShakeTime = System.currentTimeMillis()
                    }
                }
            }
        }

    }
    private var dropdownMenu: PopupWindow? = null
    private val dropdownMenuSize = IntArray(2)
    companion object {
        private const val SENSOR_VALUE = 18
        fun new(betMethod: NumType.BetMethod):BettingNumberFragment {
            val f = BettingNumberFragment()
            val b = Bundle()
            b.putSerializable(KeyContract.BetMethod,betMethod)
            f.arguments = b
            return f
        }
    }

    override fun onPause() {
        super.onPause()
        mSensorManager.unregisterListener(mSensorEventListener)
    }

    override fun onStart() {
        super.onStart()
        val mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        mSensorManager.registerListener(mSensorEventListener,mSensor,SensorManager.SENSOR_DELAY_UI)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if(hidden){
            mSensorManager.unregisterListener(mSensorEventListener)
        }else{
            val mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
            mSensorManager.registerListener(mSensorEventListener,mSensor,SensorManager.SENSOR_DELAY_UI)
        }
    }
    override fun layout(): Int {
        return R.layout.layout_betting_number
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initView() {
        method = arguments!![KeyContract.BetMethod] as NumType.BetMethod?

        // 初始化"摇一摇"功能
        mSensorManager = context?.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        mVibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        mSoundPool = SoundPool.Builder().setMaxStreams(1).build()
        mSoundId = mSoundPool.load(context,R.raw.shake_sound_male,1)
        // 初始化"机选"菜单
        dropdownMenu = createPopupWindow()
        if (method?.tipLabel == null){
            tipLabelTv?.visibility = View.GONE
        }
        tipLabelTv?.text = Html.fromHtml(method?.tipLabel?:"")
        resetResultView()
        numberSelectorView?.setChangeListener {
            val d = it
            numbers.clear()
            numbers.addAll(it)
            resetResultView()
        }
        confirmBtn?.setOnClickListener {
            if (method?.linkages != null){
                val s = method!!.linkages!!.map {
                    numbers[it]
                }
                val ss = s.findDuplicate()
                if (ss.isNotEmpty()){
                    showToast("该玩法不允许重复选号")
                    return@setOnClickListener
                }
            }
            if(allStake<1){
                showToast("请至少选择一注")
                return@setOnClickListener
            }
            val intent = Intent(context, LotteryBettingActivity::class.java)
            intentWrapper(intent)
            val betType = when(method?.id?:""){
                "1" -> Lottery.TYPE_NUM_ZX
                "2" -> Lottery.TYPE_NUM_Z3_SINGLE
                "3" -> Lottery.TYPE_NUM_Z3_MULTI
                "4" -> Lottery.TYPE_NUM_Z6
                else -> -1
            }
            val item = BettingItem(null, null,betType,allStake)
            item.betBits = numbers
            intent.putExtra(KeyContract.BettingItem, item)
            intent.putExtra(KeyContract.BetMethod,method)
            startActivity(intent)
        }
        clearBtn?.setOnClickListener {
            numberSelectorView?.clearAllChecks()
        }
        machineSelectBtn?.setOnClickListener {
            val location = IntArray(2)
            it.getLocationOnScreen(location)
            dropdownMenu?.showAtLocation(it,
                    Gravity.NO_GRAVITY,
                    location[0]-dropdownMenuSize[0],
                    location[1]-dropdownMenuSize[1]-10)
        }
        shakeBtn?.setOnClickListener {
            numberSelectorView?.randoms()
        }
        numberSelectorView?.addBitLines(method?.betLines)
    }

    private fun intentWrapper(intent: Intent):Intent{
        val lotteryId = (activity as BettingMachineActivity).currentLotteryId
        val periodNum = (activity as BettingMachineActivity).currentPeriodNum
        val isReset = (activity as BettingMachineActivity).isReset
        val resetIndex = (activity as BettingMachineActivity).resetIndex
        val lotteryName = (activity as BettingMachineActivity).currentLotteryName
        intent.putExtra(KeyContract.LotteryId,lotteryId)
        intent.putExtra(KeyContract.PeriodNum,periodNum)
        intent.putExtra(KeyContract.LotteryName,lotteryName)
        intent.putExtra(KeyContract.BetMethod,method)
        intent.putExtra(KeyContract.IsReset,isReset)
        intent.putExtra(KeyContract.ResetIndex,resetIndex)
        return intent
    }

    private fun resetResultView(){
        allStake = getAllStake()
        val text = "已选 $allStake 注\n一共 ${allStake*2} 元"
        resultLabel?.text = text
    }

    private fun getAllStake():Long{
        val lotteryId = (activity as BettingMachineActivity).currentLotteryId
        return  when(lotteryId){
            "12" -> when(method?.id){
                "1" -> if (numbers.size > 2) zxStake() else 0
                "2" -> if (numbers.size > 1) zsdStake() else 0
                "3" -> if (numbers.size > 0) zsfStake() else 0
                "4" -> if (numbers.size > 0) zlStake() else 0
                else -> 0
            }
            "16" -> when(method?.id){
                "1" -> if (numbers.size > 2) zxStake() else 0
                "3" -> if (numbers.size > 0) zsfStake() else 0
                "4" -> if (numbers.size > 0) zlStake() else 0
                else -> 0
            }
            "15" -> when(method?.id){
                "1" -> if (numbers.size > 6) zxStake() else 0
                else -> 0
            }
            else -> 0
        }
    }

    private fun zsdStake():Long{
        return if(numbers[0].size>0&&numbers[1].size > 0) 1 else 0
    }
    private fun zxStake():Long{
        var stake = 1
        for (number in numbers){
            stake *= number.size
        }
        return stake.toLong()
    }
    private fun zsfStake():Long{
        return numbers[0].size.combine(2)*2
    }

    private fun zlStake():Long{
        return numbers[0].size.combine(3)
    }
    private fun createPopupWindow(): PopupWindow {
        val view = layoutInflater.inflate(R.layout.layout_drapdown, null,false)
        val one = view.findViewById<TextView>(R.id.dropdown_one)
        val five = view.findViewById<TextView>(R.id.dropdown_five)
        val ten = view.findViewById<TextView>(R.id.dropdown_ten)
        one.setOnClickListener {
            dropdownMenu?.dismiss()
            val intent = Intent(context,LotteryBettingActivity::class.java)
            intentWrapper(intent)
            intent.putExtra(KeyContract.Gen,1)
            startActivity(intent)
        }
        five.setOnClickListener {
            dropdownMenu?.dismiss()
            val intent = Intent(context,LotteryBettingActivity::class.java)
            intentWrapper(intent)
            intent.putExtra(KeyContract.Gen,5)
            startActivity(intent)
        }
        ten.setOnClickListener {
            dropdownMenu?.dismiss()
            val intent = Intent(context,LotteryBettingActivity::class.java)
            intentWrapper(intent)
            intent.putExtra(KeyContract.Gen,10)
            startActivity(intent)
        }
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        dropdownMenuSize[0] =view.measuredWidth
        dropdownMenuSize[1] =view.measuredHeight
        val window = PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true)
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.isOutsideTouchable = true
        window.isTouchable = true
        return window
    }
}